#include "response.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

Response::Response(QObject *parent)
	: QObject(parent)
{
}

Response::Response()
{

}
Response::Response(QString code , QList<resultStruct> list)
{
    _code = code;
    _list = list;
}

Response::~Response()
{
}

QString Response::toJson() const
{
    QJsonObject ResponseObject;
    ResponseObject.insert("code", _code);

    QJsonArray resultArray;
    for (const resultStruct &s : _list )
    {
        QJsonObject temp;
        temp.insert("resultType",s.resultType);
        temp.insert("content", s.content);
        resultArray.append(temp);
    }
  
    ResponseObject.insert("results", resultArray);
    return QJsonDocument(ResponseObject).toJson();

}

Response &Response::fromJson(const QString& json)
{
    QJsonParseError error;
    const QJsonDocument& document = QJsonDocument::fromJson(json.toUtf8(), &error);
    if (QJsonParseError::NoError == error.error)
    {
        QString code;
        QList<resultStruct> list;
        QJsonObject jsonObject = document.object();

        if (jsonObject.contains("code")) {
            code = jsonObject["code"].toString();
        }
        if (jsonObject.contains("results")) {
            QJsonArray resultArray;
            resultArray = jsonObject["results"].toArray();

            for (const auto o : resultArray) {
                QJsonObject temp = o.toObject();
                resultStruct result;
                if (temp.contains("resultType") && temp.contains("content")) {
                    result.resultType = temp["resultType"].toString();
                    result.content = temp["content"].toString();
                    list.append(result);
                }

            }
        
        }

        return Response(code,list);
    }
    throw error.errorString();
}

void Response::setCode(QString code)
{
    _code = code;
}

void Response::setResultList(QList<resultStruct>& list)
{
    _list = list;
}
